package com.yami.shop.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
//import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.app.dto.OrderItemSumDto;
import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.yami.shop.bean.app.param.OrderItemParam;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.app.param.OrderRefundParam;
import com.yami.shop.bean.cashregisterapp.AppCashRegisterSystemUser;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.pay.Orderparm;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.commons.lang.StringUtils;
import org.apache.el.util.Validation;
import org.json.JSONArray;
import org.json.JSONObject;
import lombok.Data;
import com.yami.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.yami.shop.bean.model.User;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/app/order")
@Api(tags = "订单接口")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private UserAddrService userAddrService;

    @Autowired
    private AppCashRegisterSystemUserService appCashRegisterSystemUserService;

    @Autowired
    private UserService userService;

    /**
     * 生成订单信息
     */
    @PostMapping("/confirmOrder")
    public HttpResult confirmOrder(@RequestBody Orderparm orderparm){
        System.out.println("订单参数"+orderparm);
        //新增订单数据
        if(CollectionUtils.isNotEmpty(orderparm.getProductList())){
            for(Product product:orderparm.getProductList()){
                product.setShopId(SecurityUtils.getSysUser().getShopId());
            }
        }
        Long cashier = SecurityUtils.getSysUser().getUserId();
        ShopCartOrderMergerDto shopCartOrderMergerDto =  orderService.insertOrder(orderparm.getProductList(),cashier,orderparm.getPhoneNumber(),orderparm.getCid());
        return HttpResult.success(shopCartOrderMergerDto);
    }

    /**
     * 查询门店全部订单情况
     */
    @PostMapping("/getAllOrderByshopId")
    public HttpResult getAllOrderByshopId(@RequestBody Order orderParam, PageParam<Order> page){
        //当前起始页码
        //int startpageNumber = (currentPage-1)*pageNumber;
        //Long shopId = SecurityUtils.getSysUser().getShopId();
        //List<Order> orderList =  orderService.getAllOrderByshopId(shopId,pageNumber,startpageNumber);
        if(orderParam.getCurrent()!=0){
            page.setCurrent(orderParam.getCurrent());
        }
        if(orderParam.getSize()!=0){
            page.setSize(orderParam.getSize());
        }
        IPage<Order> orderList = orderService.page(page,
                new LambdaQueryWrapper<Order>()
                        .eq(orderParam.getStatus()!=null,Order::getStatus,orderParam.getStatus())
                        .eq(orderParam.getOrderNumber()!=null,Order::getOrderNumber,orderParam.getOrderNumber())
                        .eq(orderParam.getPhone()!=null,Order::getPhone,orderParam.getPhone())
                        .eq(Order::getOrderState,0)
                        .eq(Order::getRefundState,0)
                        .eq(Order::getShopId,SecurityUtils.getSysUser().getShopId())
                        .orderByDesc(Order::getCreateTime));
        if(CollectionUtils.isNotEmpty(orderList.getRecords())){
            for(Order order:orderList.getRecords()){
                String userId = order.getUserId();
                String orderNumber = order.getOrderNumber();
                Long cashier = order.getCashier();
                if(cashier!=null){
                    //查询当前收银员的信息
                    AppCashRegisterSystemUser appCashRegisterSystemUser = appCashRegisterSystemUserService.getAppCashRegisterSystemUserByUserId(cashier);
                    if(appCashRegisterSystemUser!=null){
                        String name = appCashRegisterSystemUser.getName();
                        order.setCashierName(name);
                    }
                }
                //封装用户数据
                User user = userService.getUserByUserId(order.getUserId());
                if(user!=null){
                    order.setNikeName(user.getNickName());
                    order.setUserPhone(user.getUserMobile());
                }
                //查询子订单数据
                List<OrderItem> orderItemList = orderItemService.getOrderItemsByOrderNumber(orderNumber);
                order.setOrderItems(orderItemList);
                Long addorderId = order.getAddrOrderId();
                UserAddrOrder userAddrOrder = userAddrOrderService.getById(addorderId);
                String receiver = null;
                if(userAddrOrder!=null) {
                    Long AddrId = userAddrOrder.getAddrId();
                    UserAddr userAddr = userAddrService.getById(AddrId);
                    if(userAddr!=null){
                         receiver = userAddr.getReceiver();
                    }
                  }
                order.setReceiver(receiver);
            }

        }
        return HttpResult.success(orderList);
    }

    /**
     * 待配送的订单(目前只有美团,只能查询美团待配送订单)
     */
    @PostMapping("/getDpsOrder")
    public HttpResult getDpsOrder(int pageNumber,int currentPage){
        //当前起始页码
        int startpageNumber = (currentPage-1)*pageNumber;
        Long shopId = SecurityUtils.getSysUser().getShopId();
        List<Order> orderList = orderService.getDpsOrder(shopId,pageNumber,startpageNumber);
        if(CollectionUtils.isNotEmpty(orderList)){
            for(Order order:orderList){
                String userId = order.getUserId();
                    String orderNumber = order.getOrderNumber();
                    //查询子订单数据
                    List<OrderItem> orderItemList = orderItemService.getOrderItemsByOrderNumber(orderNumber);
                    order.setOrderItems(orderItemList);
                    Long addorderId = order.getAddrOrderId();
                    UserAddrOrder userAddrOrder = userAddrOrderService.getById(addorderId);
                    String receiver = null;
                    if(userAddrOrder!=null) {
                        Long AddrId = userAddrOrder.getAddrId();
                        UserAddr userAddr = userAddrService.getById(AddrId);
                    if(userAddr!=null){
                        receiver = userAddr.getReceiver();
                    }
                }
                order.setReceiver(receiver);
            }

        }
        return HttpResult.success(orderList);
    }

    /**
     * 查询门店待快递订单
     */
    @PostMapping("/getDkdOrder")
    public HttpResult getDkdOrder(int pageNumber,int currentPage){
        //当前起始页码
        int startpageNumber = (currentPage-1)*pageNumber;
        Long shopId = SecurityUtils.getSysUser().getShopId();
        List<Order> orderList = orderService.getDkdOrder(shopId,pageNumber,startpageNumber);
        if(CollectionUtils.isNotEmpty(orderList)){
            for(Order order:orderList){
                String userId = order.getUserId();
                String orderNumber = order.getOrderNumber();
                //查询子订单数据
                List<OrderItem> orderItemList = orderItemService.getOrderItemsByOrderNumber(orderNumber);
                order.setOrderItems(orderItemList);
                Long addorderId = order.getAddrOrderId();
                UserAddrOrder userAddrOrder = userAddrOrderService.getById(addorderId);
                String receiver = null;
                if(userAddrOrder!=null) {
                    Long AddrId = userAddrOrder.getAddrId();
                    UserAddr userAddr = userAddrService.getById(AddrId);
                    if(userAddr!=null){
                        receiver = userAddr.getReceiver();
                    }
                }
                order.setReceiver(receiver);
            }

        }
        return  HttpResult.success(orderList);
    }




    /**
     * 发快递(填写物流信息)
     */
    @PostMapping("/expressDelivery")
    public HttpResult expressDelivery(String orderNumber,Long dvyId,String dvyFlowId){
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        order.setDvyId(dvyId);
        order.setDvyFlowId(dvyFlowId);
        order.setStatus(3);
        orderService.updateById(order);
        return HttpResult.success();
    }

    /*
    销售明细*/
    @PostMapping("/selectOrder")
    public HttpResult selectOrder(@RequestBody OrderItemParam orderItemParam)
    {
        OrderItemSumDto orderItemSumDto= new OrderItemSumDto();
        Long shopId=SecurityUtils.getSysUser().getShopId();

        List<Long> orderItemIdlist=new ArrayList();//存放当天所有订单的order_item_id

        /* status=5 order_state=0 的当前店铺的所有订单**/
        List<Order> orderRecords=orderService.getOrderListByTodayShopAState(shopId,orderItemParam.getStartTime(),orderItemParam.getEndTime());

        if(CollectionUtil.isNotEmpty(orderRecords)) {
                for (Order order : orderRecords) {
                List<OrderItem> orderItemsRecords = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());//根据order_number获取tz_order_item里的订单
                if(CollectionUtil.isNotEmpty(orderItemsRecords))
                {
                    for (OrderItem orderItem : orderItemsRecords) {
                        orderItemIdlist.add(orderItem.getOrderItemId());
                    }
                }
            }
        }
        List<OrderItem> orderItems=null;
        if(orderItemIdlist.size()>0)
        {
//            List<Long> orderItemIdlistNew = new ArrayList<Long>(new TreeSet<Long>(orderItemIdlist));
            orderItems=orderItemService.getSumOrderByOrderItemId(orderItemIdlist,orderItemParam.getStart(),orderItemParam.getSize());
        }
        int allCount=0;
        BigDecimal allMoney=new BigDecimal("0.00");
        BigDecimal totalDiscountMoney=new BigDecimal("0.00");
        if(CollectionUtil.isNotEmpty(orderItems)) {
            orderItemSumDto.setTotalResult(orderItems.size());
            for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext(); ) {
                OrderItem orderItem = iterator.next();
                allMoney = allMoney.add(new BigDecimal(orderItem.getTotalMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
                totalDiscountMoney = totalDiscountMoney.add(new BigDecimal(orderItem.getDisCountMoney()).setScale(2,BigDecimal.ROUND_HALF_UP));
                allCount += orderItem.getProdCount();
            }
        }
        else {
            orderItemSumDto.setTotalResult(0);
        }
        orderItemSumDto.setOrderItemList(orderItems);
        orderItemSumDto.setSaleNumber(allCount);//合计销量
        orderItemSumDto.setSaleAccount(allMoney);//合计销售额
        orderItemSumDto.setTotalDiscountMoney(totalDiscountMoney);//合计优惠金额
        return HttpResult.success(orderItemSumDto);
    }

    /**
退款明细*/
    @PostMapping("/selectOrderRefund")
    public HttpResult selectOrderRefund(@RequestBody OrderRefundParam orderRefundParam, PageParam<OrderRefund> page)
    {
//        String timestamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date());   // eg:2021-02-27
        if(orderRefundParam.getSize()!=null)
        {
            page.setSize(orderRefundParam.getSize());
        }
        if(orderRefundParam.getCurrent()!=null)
        {
            page.setCurrent(orderRefundParam.getCurrent());
        }
        IPage<OrderRefund> records = orderRefundService.page(page,
                new LambdaQueryWrapper<OrderRefund>()
                        .eq(OrderRefund::getShopId,SecurityUtils.getSysUser().getShopId())
                        .eq(StringUtils.isNotEmpty(orderRefundParam.getOrderNumber()),OrderRefund::getOrderNumber,orderRefundParam.getOrderNumber())
                        .eq(orderRefundParam.getReturnMoneySts()!=null,OrderRefund::getReturnMoneySts,orderRefundParam.getReturnMoneySts())//处理退款状态 1为退款成功
                        .eq(orderRefundParam.getApplyType()!=null,OrderRefund::getApplyType,orderRefundParam.getApplyType())//申请类型 1仅退款  2退款退货
                        .eq(orderRefundParam.getRefundSts()!=null,OrderRefund::getRefundSts,orderRefundParam.getRefundSts())//处理状态
                        .ge(OrderRefund::getApplyTime,orderRefundParam.getStartTime())
                        .le(OrderRefund::getApplyTime,orderRefundParam.getEndTime())
                        .orderByDesc(OrderRefund::getApplyTime));
        return HttpResult.success(records);
    }

}
